import os
import uuid

from scipy.io import wavfile


def export_audio(video, outDir):
    output = "{0}{1}.wav".format(outDir, uuid_str())
    cmd = "ffmpeg -i {0} -f wav -ar 16000 {1}".format(video, output)
    print(cmd)
    os.system(cmd)
    return output


def cut(start, end, input, output):
    cmd = "ffmpeg -ss {0} -to {1} -accurate_seek -i {2} -vcodec libx264 -acodec aac -avoid_negative_ts 1 {3} -y".format(
        start, end, input, output)
    print(cmd)
    os.system(cmd)


def merge(list, output, outDir):
    filename = outDir + uuid_str() + ".txt"
    with open(filename, 'w') as file:
        for i in list:
            file.write("file '{0}'\n".format(i))
    cmd = "ffmpeg -f concat -safe 0 -i {0} -c copy {1} -y".format(filename, output)
    os.system(cmd)
    os.remove(filename)
    os.chdir(outDir)
    for item in list:
        os.remove(item)


'''
分析音频波形获取要保留的视频时间片段
min_time 最小时间 秒
min_volumn 最小音量
'''


def getCutTime(audio, min_time=0.01, min_volumn=2000):
    print("start to analysis audio wave")
    # file = wave.open(audio)
    # a = file.getparams().nframes  # 帧总数
    # f = file.getparams().framerate  # 采样频率
    # file.close()


    sample_frequency, audio_sequence = wavfile.read(audio) #sample_frequency 采样频率
    rows, cols = audio_sequence.shape
    sample_time = 1 / sample_frequency  # 采样点的时间间隔,每一帧音频的播放时间
    time = rows / sample_frequency  # 声音信号的长度

    start = 0
    flag = False
    # 计算要减掉的帧数
    list = []
    for i in range(rows):
        left = abs(audio_sequence[i, 0])
        right = abs(audio_sequence[i, 1])
        if left < min_volumn and right < min_volumn:
            if not flag:
                start = i
                flag = True  # 开启游标状态
        else:
            if flag:
                list.append([start, i])
                start = 0
                flag = False  # 关闭游标状态
    # 去掉时间间隔短的游标
    ll = []
    for t in list:
        #时间范围超过阈值才可取
        if t[1] - t[0] > min_time * sample_frequency:
            ll.append(t);
    # 帧数转时间
    list3 = []
    for t in ll:
        list3.append([t[0] / sample_frequency , t[1] / sample_frequency ])
    # 切割时间转换为保留时间
    list4 = [(0, list3[0][0])]
    for i in range(0, len(list3) - 1):
        list4.append((list3[i][1], list3[i + 1][0]))
    list4.append((list3[len(list3) - 1][1], time))
    print('分析音频波形成功')
    os.remove(audio)
    return list4


def uuid_str():
    return str(uuid.uuid4()).replace("-", "")


def auto_cut(input, outDir, min_time = 0.1, min_volume = 2000):
    if not outDir.endswith("/"):
        outDir += "/"
    if not os.path.exists(outDir):
        os.makedirs(outDir)
        print("创建输出文件夹成功！")
    filepath, filename = os.path.split(input)
    outfile = outDir + filename

    audio = export_audio(input, outDir)
    list = getCutTime(audio, min_time, min_volume)
    arr = []
    temp = uuid_str()
    i = 1
    for item in list:
        if item[1] > 0:
            output = outDir + temp + "-" + str(i) + ".mp4"
            cut(item[0], item[1], input, output)
            arr.append(temp + "-" + str(i) + ".mp4")
            i += 1

    merge(arr, outfile, outDir)
    print('success')
    os.startfile(outDir)


if __name__ == "__main__":
    auto_cut(r'C:\Users\lty-017\Desktop\a\a.mp4', 'd:/video',0.1,4000)
